import Flutter
import UIKit
import AdSupport
import KeychainAccess
import AppTrackingTransparency

public class SwiftDeviceUtilPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "device_util", binaryMessenger: registrar.messenger())
    let instance = SwiftDeviceUtilPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "getPlatformVersion":
        result("iOS " + UIDevice.current.systemVersion)
        break
    case "version":
        result(Bundle.main.infoDictionary?["CFBundleShortVersionString"] ?? "")
        break
    case "versionCode":
        result(Bundle.main.infoDictionary?["CFBundleVersion"] ?? "")
        break
    case "appName":
        result(Bundle.main.infoDictionary?["CFBundleDisplayName"] ?? "")
        break
    case "idfa":
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                if (status == .authorized){
                    result(ASIdentifierManager.shared().advertisingIdentifier.uuidString)
                }else{
                    result("")
                }
            })
        } else {
            if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
                result(ASIdentifierManager.shared().advertisingIdentifier.uuidString)
            }else{
                result("")
            }
        }
        break
    case "bundleInfo":
        let key = (call.arguments as? [String:Any?])?["key"]
        if (key == nil){
            result("")
        }else{
            result(Bundle.main.infoDictionary?[key as! String])
        }
        break
    case "uniqueDeviceId":
        result(getUuid())
        break
    case "deviceType":
        result(UIDevice.current.model);
        break
    case "openAppSetting":
        if let url = URL.init(string: UIApplication.openSettingsURLString) {
            if UIApplication.shared.canOpenURL(url) {
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                } else {
                    UIApplication.shared.openURL(url)
                }
            }
        }
        result(true)
        break
    case "androidId":
        // iOS 没有 Android ID，返回空字符串
        result("")
        break
    case "macAddress":
        // iOS 无法获取 MAC 地址，返回空字符串
        result("")
        break
    case "oaid":
        // iOS 没有 OAID，返回空字符串
        result("")
        break
    case "ipAddress":
        // iOS 获取 IP 地址比较复杂，暂时返回空字符串
        result("")
        break
    case "metaValue":
        // iOS 没有 Android 的 meta-data，返回空字符串
        result("")
        break
    case "assets":
        // iOS 读取 assets 文件
        let fileName = (call.arguments as? [String:Any?])?["file"] as? String
        if let fileName = fileName, let path = Bundle.main.path(forResource: fileName, ofType: nil) {
            do {
                let content = try String(contentsOfFile: path, encoding: .utf8)
                result(content)
            } catch {
                result("")
            }
        } else {
            result("")
        }
        break
    case "hume":
        // iOS 没有 Hume 渠道，返回空字符串
        result("")
        break
    case "tencentChannel":
        // iOS 没有 Tencent 渠道，返回空字符串
        result("")
        break
    case "ksChannel":
        // iOS 没有 KS 渠道，返回空字符串
        result("")
        break
    case "sourceDir":
        result(Bundle.main.bundlePath)
        break
    case "installApk":
        // iOS 无法安装 APK，返回 false
        result(false)
        break
    case "sdkVersion":
        result(UIDevice.current.systemVersion)
        break
    case "initOaid":
        // iOS 没有 OAID，返回成功
        result(nil)
        break
    case "metrics":
        let screen = UIScreen.main
        let bounds = screen.bounds
        let scale = screen.scale
        let metrics: [String: Any] = [
            "widthPx": Int(bounds.width * scale),
            "heightPx": Int(bounds.height * scale),
            "xDpi": 72.0, // iOS 默认 DPI
            "yDpi": 72.0
        ]
        result(metrics)
        break
    default:
        result(FlutterMethodNotImplemented)
        break
    }
  }
    
    private func getUuid()->String{
        let keychain = Keychain(service: "com.xjb.deviceUtil.uuid")
        let uuid = keychain["uuid"] ?? ""
        if uuid.isEmpty {
            let temp = UIDevice.current.identifierForVendor?.uuidString ?? ""
            keychain["uuid"] = temp
            return temp
        }
        return uuid
    }
}
